<?
// This is a test
function getEvents($mo,$yr,$size=null,$startDate=null,$endDate=null,$scope=null,$renderType='calendar') {
	/*
	 * Here's what we're going to do
	 * We need to make this function multi-purpose
	 * Pass in start and end dates too
	 * Return data as HTML, JSON, Array
	 */
	global $dbname,$db,$db_selected,$monthNameLongArray;
	$where = '';
	/*
	 * Get calendar data
	 */
	/*
	 * Format WHERE clause
	 */
	if ( !empty($mo) && !empty($yr) ) {
		$where .= "(MONTHNAME(StartDate) = '$mo' AND YEAR(StartDate) = '$yr') OR ";
		$where .= "(MONTHNAME(EndDate) = '$mo' AND YEAR(EndDate) = '$yr')";
		
		/*
		 * Get month number
		 */
		for($a=0;$a<=11;$a++) {
			if ($mo == $monthNameLongArray[$a]) {
				$monthNumber = $a+1;
			}
		}
	} else {	
		if (!empty($startDate)) {
			$where .= "StartDate >= '$startDate'";
		}
		if ( !empty($startDate) && !empty($endDate) ) {
			$where .= ' AND ';
		}
		if (!empty($endDate)) {
			$where .= "EndDate <= '$endDate 23:59:59";
		}
	}	
	
	if ($scope == 'public') {
		$scope = ' AND C.Public = 1';
	} elseif ($scope == 'private') {
		$scope = ' AND C.Public = 0 AND OrgFlag = '.$_SESSION['org'].' ';
	} else {
		$scope = ' ';
	}	
		
	$sql  = "SELECT 
				C.EventID,C.EventName,C.EventCat,C.EventDescription,C.StartDate,C.EndDate,C.Public,C.OrgFlag,
				MC.CatTitle,MC.Misc
				FROM cdc_Calendar C
				LEFT JOIN cdc_sysCategory MC ON C.EventCat = MC.CatID
				WHERE 
				(
					$where					
					$scope
				)
					AND	C.Active = 1
					AND C.Deleted = 0
				ORDER BY StartDate";
	$result = mysql_db_query($dbname,$sql);
	$events = mysql_num_rows($result);
	
	$origDateTime = '';
	$stringJSON   = '({"Events":[';		
	$e=0;
	while ($valueEvent = mysql_fetch_array($result)) {	
		/*
		 * Block events with Public = 0 and OrgFlag != org
		 */
		if ( ($valueEvent['Public'] == 0) && ($valueEvent['OrgFlag'] != $_SESSION['org']) ) {
		} else {			
			$startDate = new Zend_Date($valueEvent['StartDate'], Zend_Date::ISO_8601, 'en_US');
			$newStartDate = $startDate->toString('MMM d, h:m a');
			$valueEvent['StartDateFormat'] = $newStartDate;
			                        
                        /* 
                         * Format end date/time string
                         */
                         $valueEvent['EndDateFormat'] = '';
                         $dateEndArray = explode(' ',$valueEvent['EndDate']);
                         if ($dateEndArray[0] != '0000-00-00') {
                             $endDate = new Zend_Date($valueEvent['EndDate'], Zend_Date::ISO_8601, 'en_US');
                             $newEndDate = $endDate->toString('MMM d, h:m a');
                             $valueEvent['EndDateFormat'] = $newEndDate;
                         } elseif ($dateEndArray[1] != '00:00:00') {
                             $endDate = new Zend_Date($valueEvent['EndDate'], Zend_Date::ISO_8601, 'en_US');
                             $newEndDate = $endDate->toString('h:m a');
                             $valueEvent['EndDateFormat'] = $newEndDate;
                         }
                          
			if ($renderType == 'json') {
				$stringJSON .= Zend_Json::encode($valueEvent).',';
			} elseif ($renderType == 'array') {
			
			} elseif ($renderType == 'calendar') {
				$itemID       = $valueEvent['EventID'];
				$itemTitle    = stripslashes($valueEvent['EventName']); 
				$itemDateTime = $valueEvent['StartDate'];
				$itemEndDate  = $valueEvent['EndDate'];
				$itemType     = $valueEvent['EventCat'];
				$itemTypeName = $valueEvent['CatTitle'];
                                $itemColor    = $valueEvent['Misc'];
				$itemDesc     = $valueEvent['EventDescription'];
				
				/*
				 * Get dates between start/end dates...if end date exists
				 */
				$datesArray = getDatesBetweenDates($valueEvent['StartDate'],$valueEvent['EndDate']);
									
				for($aa=0;$aa<=(count($datesArray)-1);$aa++) {
					$itemDateTime = $datesArray[$aa];	
					
					// What day number?
					$dateTimeArray = explode(' ',$itemDateTime);
					$dateArray = explode('-',$dateTimeArray[0]);
					$thisDay   = $dateArray[2];
					$thisMonth = $dateArray[1];
					if ($thisMonth == $monthNumber) {
						/*
						 * Make sure we're only displaying events
						 * for the month we're currently viewing.
						 * For ex. if there's an event that spans 2
						 * months, we only want to render the event for 
						 * the current month.
						 */
						if (substr($thisDay,0,1) == '0') {
							$thisDay = substr($thisDay,1,1);
						}
						
						if ($origDateTime != $dateTimeArray[0]) {
							/*
							 * Are we moving to the next day?
							 * If so, reset counter e 
							 */
							$e=0;
							while (!empty($eventArray[$thisDay][$e])) {
								$e++;	
							}
							$origDateTime = $dateTimeArray[0];
						}
								
						// Format DateTime
						$dateEvent = new Zend_Date($itemDateTime, Zend_Date::ISO_8601, 'en_US');
						$newTime = $dateEvent->toString('h:m a');
						$extQtip = '<b>'.$newTime.'</b> '.$itemTitle;
                                                
						if (!empty($itemDesc)) {
							$extQtip .= '<br />'.$itemDesc;
						}	
                                                $extQtip = str_replace("'","`",$extQtip);
                                                $extQtip = str_replace('"','',$extQtip);
                                                if (empty($itemColor)) {
							$itemColor = '#ccc';
						}					
						if ($size == 'small') {
							$itemString = substr($itemTypeName,0,1);
                                                        $eventArray[$thisDay][$e] = '<div id="eventContainer'.$itemID.'"><div class="calEventBarSmall" style="background: '.$itemColor.'; text-align: center;" onClick="calendarUpdateObj.getEventData('.$itemID.',\'view\'); return false;" ext:qtip="'.$extQtip.'">'.$itemString.'</div></div>'; 
						} elseif ($size == 'medium') {
							$itemString = $itemTypeName;
                                                        $eventArray[$thisDay][$e] = '<div id="eventContainer'.$itemID.'"><div class="calEventBarSmall" style="background: '.$itemColor.';" onClick="calendarUpdateObj.getEventData('.$itemID.',\'view\'); return false;" ext:qtip="'.$extQtip.'">'.$itemString.'</div></div>'; 
                                                } else {
							$itemString = '<b>'.$newTime.'</b> '.$itemTitle;
							$eventArray[$thisDay][$e]  = '<div id="eventContainer'.$itemID.'"><div class="calEventBar" style="border-bottom: 3px solid '.$itemColor.';" onClick="calendarUpdateObj.getEventData('.$itemID.',\'view\'); return false;"><div class="calEventContainer">'.$itemString.'</div></div></div>'; 
						}		
						$e++;
					}	
				}		
			}	
			//$e++;
		}	
	}	
	if ($renderType == 'json') {
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';
		$returnString = $stringJSON;
		return $returnString;
	}
	if ($renderType == 'calendar') {
		return $eventArray;	
	}	
}

function displayCalendar($mo=null,$yr=null,$size=null) {
	global $calendarString,$dbname,$db,$db_selected;
	global $newDate,$newTime;
		
	global $dayArray,$monthNameArray,$monthNumArray,$monthNameLongArray;
	
	if (empty($mo)) { $mo = date('n'); }
	if (empty($yr)) { $yr = date('Y'); }
	if (empty($size)) { $size = '0'; }	
	$link_month = $mo;
	$link_year = $yr;
	
	$calendarString = '';
	
	$theday = date(w, mktime(0, 0, 0, $mo, 1, $yr));
	$daysinmonth = date("t", mktime(0, 0, 0, $mo, 1, $yr));
	
	/***** CALENDAR HEADER ***********************************************/
	
	$calendarString .= '<div style="width: 99%;"><table id="calHeader"><tr>';
	$currentYear = $yr;
	if ($mo == 1) { $yr = ($yr - 1); $mo = 13; }
	$calendarString .= '<td class="left">
						<a href="#" onClick="calendarNavigateObject.newMonth(\''.($mo - 1).'\',\''.$yr.'\',\''.$size.'\'); return false;" title="'.$monthNameLongArray[$mo-2].' '.$yr.'">
						<img src="'.$pre.'images/button_prev.gif" style="border: none;" alt="'.$monthNameLongArray[$mo-2].' '.$yr.'"></a></td>';
	$calendarString .= '<td class="center"><b>'.$monthNameLongArray[$link_month-1].' '.$currentYear.'</b></td>';
							
	if ($mo == 12) { $yr = ($yr + 1); $mo = 0; }
	if ($mo == 13) { $yr = $yr + 1; $mo = 1; }
	$calendarString .= '<td class="right">
						<a href="#" onClick="calendarNavigateObject.newMonth(\''.($mo + 1).'\',\''.$yr.'\',\''.$size.'\'); return false;" title="'.$monthNameLongArray[$mo].' '.$yr.'">
						<img src="'.$pre.'images/button_next.gif" style="border: none;" alt="'.$monthNameLongArray[$mo].' '.$yr.'"></a></td>
						</tr>
						</table>
						<table style="font-size: 1em;" class="calWrap"><tr>';
	
	// Print day header
	for ($i=0;$i<7;$i++) {
		if ($size!='small') {
			$calendarString .= '<th>'.substr($dayArray[$i],0,3).'</th>';
		} else {
			$calendarString .= '<th style="text-align: center;">'.substr($dayArray[$i],0,1).'</th>';
		}
	}	
	$calendarString .= '</tr>';
	/*
	 * End day header
	 */
	
	/*
	 * Get calendar data
	 */
	$eventArray = getEvents($monthNameLongArray[$link_month-1],$yr,$size);
	
	/*
	 * Print the actual calendar
	 */
	$calendarString .= '<tr>';
	for ($i=0;$i<$theday;$i++) {
    	$calendarString .= '<td style="background: #eee;">&nbsp;</td>';
	}
	for ($list_day=1;$list_day<=$daysinmonth;$list_day++) {
		$complete_date = $yr.'-'.$mo.'-'.$list_day;
		if ( ($list_day == date('d')) && ($link_month == date('n')) ) {
			$class     = 'class="today"'; 
		} else { 
			$class     = '';	
		}
		$calendarString .= '<td id="'.$complete_date.'" style="width: 14%; height: 50px;" '.$class.'>';
		$calendarString .= '<div style="text-align: right;">'.$list_day.'</div>';
		// Render events for this day [$list_day]
		if (count($eventArray[$list_day])>0) {
			foreach($eventArray[$list_day] as $value) {
				if (!empty($value)) {
					$calendarString .= $value;
				}
			}
			/*
			for($ei=0;$ei<=(count($eventArray[$list_day])-1);$ei++) {
				$calendarString .= $eventArray[$list_day][$ei];
			}
			*/
		}
		$calendarString .= '</td>';
	    if ($theday == 6) {
	    	$calendarString .= '</tr>';
	        $calendarString .= '<tr>';
	        $theday = -1;
	    }	    
	    $theday++;
	}
	
	$calendarString .= '</tr></table></div>';	
	return $calendarString;				
}

function displayCalendarFull($mo=null,$yr=null) {
	global $dbname,$db,$db_selected,$dayArray;
	global $monthNameLongArray;
	
	if (empty($mo)) { 
		$mo = date('n'); 
		$currentMonth = date('F');
	} else {
		$currentMonth = $monthNameLongArray[$mo-1];
	}
	if (empty($yr)) { $yr = date('Y'); }
	$link_month = $mo;
	$link_year = $yr;
	
	$calendarString = '';
	
	$theday = date(w, @mktime(0,0,0,$mo,1,$yr));
	$daysinmonth = date("t", @mktime(0,0,0,$mo,1,$yr));
	
	$monthNumArray = array('1','2','3','4','5','6','7','8','9','10','11','12');	
	
	$calendarString .= '<div id="calendarContent">';
	$calendarString .= '<table class="calWrapBig"><tr>';
	/*
	 * Print day of the week header
	 */
	for ($i=0;$i<7;$i++) {
		$calendarString .= '<th>'.$dayArray[$i].'</th>';
	}	
	$calendarString .= '</tr>';
	/*
	 * End day of the week header
	 */

	
	/*
	 * Get calendar data
	 */
	$eventArray = getEvents($currentMonth,$yr);
	
	/*
	 * Print the actual calendar
	 */
	$calendarString .= '<tr>';
	for ($i=0;$i<$theday;$i++) {
    	$calendarString .= '<td class="empty">&nbsp;</td>';
	}
	$daysInRow = 0;
	for ($list_day=1;$list_day<=$daysinmonth;$list_day++) {
		if (strlen($list_day) == 1) {
			$link_day = '0'.$list_day;
		} else {
			$link_day = $list_day;
		}
		if (strlen($link_month) == 1) {
			$link_month = '0'.$link_month;
		}
		$complete_date = $link_year.'-'.$link_month.'-'.$link_day;
		
		if ( ($list_day == date('d')) && ($link_month == date('n')) ) { 
			$tdClass     = 'today'; 
			$dayNumClass = 'calDayNumToday';
			$dayNumBG    = 'url(../images/bgMenuSelect.gif) repeat-x left';
		} else { 
			$tdClass     = '';	
			$dayNumClass = 'calDayNum';
			$dayNumBG    = '#f6f6f6';
		}
	    $calendarString .= '<td id="'.$complete_date.'" class="'.$tdClass.'">';
	    
		    // Render day number
			$calendarString .= '
				<div class="'.$dayNumClass.'" 
					onMouseOver="calendarSupportObj.calDayNumHover('.$list_day.',\''.$dayNumClass.'\');" 
					onMouseOut="calendarSupportObj.calDayNumUnHover('.$list_day.',\''.$dayNumClass.'\');" 
					onClick="calendarSupportObj.openEventForm(\''.$complete_date.'\',\'add\'); return false;" 
					title="Click to add event for this day" 
					id="calDayNum'.$list_day.'">
				'.$list_day.'&nbsp;</div>';
			$calendarString .= '<div style="width: 100%;">';
			
			// Render events for this day [$list_day]
			if ( (count($eventArray[$list_day])>0) || (count($taskArray[$list_day])>0) ) {
				for($ei=0;$ei<=(count($eventArray[$list_day])-1);$ei++) {
					$calendarString .= $eventArray[$list_day][$ei];
				}
				for($ei=0;$ei<=(count($taskArray[$list_day])-1);$ei++) {
					$calendarString .= $taskArray[$list_day][$ei];
				}
			} else {
				$calendarString .= '<img src="images/spacer.gif" style="height: 75px;" />';
			}
			
			$calendarString .= '</div>';
			$daysInRow++;
		$calendarString .= '</td>'."\n";
	    if ($theday == 6) {
	    	$daysInRow = 0;
	    	$calendarString .= '</tr>'."\n";
	        $calendarString .= '<tr>';
	        $theday = -1;
	    }
	    $theday++;
	}
	
	if ($daysInRow<6) {
		for($dir=$daysInRow;$dir<=6;$dir++) {
			$calendarString .= '<td class="empty">&nbsp;</td>';
		}
	}
	
	$calendarString .= '</tr></table>';	
	$calendarString .= '</div>';
	$calendarString .= '~~|~~'.$currentMonth.'~~|~~'.$yr;
	return $calendarString;				
}

function saveEvent($phpJSON) {
	global $dbname, $db, $db_selected;
	global $calendarString;
	
	// Decode JSON
     $phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$eID            = $phpArray['eID'];
	$action         = $phpArray['action'];
	$completeDate   = $phpArray['completeDate'];
	$mo             = $phpArray['mo'];
	$yr             = $phpArray['yr'];
	$eType          = $phpArray['eType'];
	$eName          = fieldToDB($phpArray['eName']);
	//$eDesc          = urldecode($phpArray['eDesc']);
     $eDesc          = fieldToDBWithHTML($phpArray['eDesc']);
	$eURL           = fieldToDB($phpArray['eURL']);
	$eRegURL        = fieldToDB($phpArray['eRegURL']);
	$eDateStart     = $phpArray['eDateStart'];
	$eDateEnd       = $phpArray['eDateEnd'];
	$eHourStart     = $phpArray['eHourStart'];
	$eMinStart      = $phpArray['eMinStart'];
	$eAPStart       = $phpArray['eAPStart'];
	$eHourEnd       = $phpArray['eHourEnd'];
	$eMinEnd        = $phpArray['eMinEnd'];
	$eAPEnd         = $phpArray['eAPEnd'];
	$eLocation      = fieldToDB($phpArray['eLocation']);
	$eAddress       = fieldToDB($phpArray['eAddress']);
	$eState         = $phpArray['eState'];
	$eCity          = fieldToDB($phpArray['eCity']);
	$eZip           = fieldToDB($phpArray['eZip']);
	$eContactPerson = fieldToDB($phpArray['eContactPerson']);
	$eContactPhone  = fieldToDB($phpArray['eContactPhone']);
	$eContactEmail  = fieldToDB($phpArray['eContactEmail']);
	$eVenueSize     = fieldToDB($phpArray['eVenueSize']);
	$ePublic        = $phpArray['ePublic'];
	$eSpeakers      = fieldToDB($phpArray['eSpeakers']);
	$eReg           = $phpArray['eReg'];
		
	/*
	 * Format some stuff
	 */
	$startDateTime = extDateToMySQL($eDateStart).' '.formatTimeString($eHourStart,$eMinStart,$eAPStart);
	$endDateTime   = extDateToMySQL($eDateEnd).' '.formatTimeString($eHourEnd,$eMinEnd,$eAPEnd);
	
	if ($eRegURL == 'http://') {
		$eRegURL = '';
	}
	if ($eURL == 'http://') {
		$eURL = '';
	}
		
	if ( ($eType == 'Select...') || empty($eType) ) {
		$eType = '';
	}
	if ( ($eState == 'Select...') || empty($eState) ) {
		$eState = '';
	}
	
	if ($action == 'add') {
		$sql = "INSERT into cdc_Calendar (
					EventName,
					EventCat,
					EventDescription,
					StartDate,
					EndDate,
					Location,
					LocationAddress,
					LocationCity,
					LocationState,
					LocationZip,
					ContactPerson,
					ContactPhone,
					ContactEmail,
					ContactURL,
					RegistrationRequired,
					RegistrationLink,
					Speakers,
					VenueSize,
					Public,
					OrgFlag,
					DateUpdate,
					Userid,
					Active
				) values (
					'$eName',
					'$eType',
					'$eDesc',
					'$startDateTime',
					'$endDateTime',
					'$eLocation',
					'$eAddress',
					'$eCity',
					'$eState',
					'$eZip',
					'$eContactPerson',
					'$eContactPhone',
					'$eContactEmail',
					'$eURL',
					'$eReg',
					'$eRegURL',
					'$eSpeakers',
					'$eVenueSize',
					'$ePublic',
					'".$_SESSION['org']."',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."',
					'1'
				)";		
	} elseif ($action == 'edit') {
		$sql = "UPDATE cdc_Calendar SET
					EventName            = '$eName',
					EventCat             = '$eType',
					EventDescription     = '$eDesc',
					StartDate            = '$startDateTime',
					EndDate              = '$endDateTime',
					Location             = '$eLocation',
					LocationAddress      = '$eAddress',
					LocationCity         = '$eCity',
					LocationState        = '$eState',
					LocationZip          = '$eZip',
					ContactPerson        = '$eContactPerson',
					ContactPhone         = '$eContactPhone',
					ContactEmail         = '$eContactEmail',
					ContactURL           = '$eURL',
					RegistrationRequired = '$eReg',
					RegistrationLink     = '$eRegURL',
					Speakers             = '$eSpeakers',
					VenueSize            = '$eVenueSize',
					Public               = '$ePublic',
					DateUpdate           = '".date('Y-m-d')."',
                    UseridLastUpdate     = '".$_SESSION['userid']."'
				WHERE
				EventID = '$eID'";
	}
	$result = mysql_db_query($dbname,$sql);
	$completeDateArray = explode('-',$completeDate);
	$calendarString = displayCalendarFull($mo,$yr);
	return $calendarString;	

	//return 'phpJSON: '.$phpJSON;
}

function getEvent($eventID,$action) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_Calendar WHERE EventID = '$eventID'";
	$result = mysql_db_query($dbname,$sql);
	$rowEvent = mysql_fetch_assoc($result);
		
	if ($action == 'view') {
		/*
		 * Convert dates
		 */
		$dateStart    = new Zend_Date($rowEvent['StartDate'], Zend_Date::ISO_8601, 'en_US');
		$newDateStart = $dateStart->toString('MMM d, Y h:m a');
                
                /* 
                 * Format end date/time string
                 */
                 $newDateEnd = '';
                 $dateEndArray = explode(' ',$rowEvent['EndDate']);
                 if ($dateEndArray[0] != '0000-00-00') {
                     $endDate = new Zend_Date($rowEvent['EndDate'], Zend_Date::ISO_8601, 'en_US');
                     $newDateEnd = $endDate->toString('MMM d, h:m a');
                 } elseif ($dateEndArray[1] != '00:00:00') {
                     $endDate = new Zend_Date($rowEvent['EndDate'], Zend_Date::ISO_8601, 'en_US');
                     $newDateEnd = $endDate->toString('h:m a');
                 }                
		
		$rowEvent['StartDate'] = $newDateStart;
		$rowEvent['EndDate']   = $newDateEnd;
		
		/*
		 * Format location
		 */
		$location = '';
		if (!empty($rowEvent['Location'])) {
			$location .= $rowEvent['Location'].'<br />';
		}
		if (!empty($rowEvent['LocationAddress'])) {
			$location .= $rowEvent['LocationAddress'].'<br />';
		}
		if (!empty($rowEvent['LocationCity'])) {
			$location .= $rowEvent['LocationCity'];
		}
		if (!empty($rowEvent['LocationState'])) {
			$location .= ' '.$rowEvent['LocationState'];
		}
		if (!empty($rowEvent['LocationZip'])) {
			$location .= ' '.$rowEvent['LocationZip'];
		}
		$rowEvent['LocationString'] = $location;
		
		/*
		 * Try to make Google location string
		 */
		if (	
				!empty($rowEvent['LocationCity'])  && 
				!empty($rowEvent['LocationState']) && 
				!empty($rowEvent['LocationAddress'])) {
			
			$rowEvent['GoogleLocation'] = $rowEvent['LocationAddress'].' '.$rowEvent['LocationCity'].' '.$rowEvent['LocationState'].' '.$rowEvent['LocationZip'];	
		} else {
			$rowEvent['GoogleLocation'] = 0;
		}
		
		/*
		 * Check for properly formatted URL's
		 */
		if (!empty($rowEvent['ContactURL'])) {
			if (substr($rowEvent['ContactURL'],0,7) != 'http://') {
				$rowEvent['ContactURL'] = 'http://'.$rowEvent['ContactURL'];
			}
		}
		if (!empty($rowEvent['RegistrationLink'])) {
			if (substr($rowEvent['RegistrationLink'],0,7) != 'http://') {
				$rowEvent['RegistrationLink'] = 'http://'.$rowEvent['RegistrationLink'];
			}
		}
		
		/*
		 * Format contact string
		 */
		$contact = '';
		if (!empty($rowEvent['ContactPerson'])) {
			$contact .= $rowEvent['ContactPerson'].'<br />';
		}
		if (!empty($rowEvent['ContactPhone'])) {
			$contact .= 'Ph: '.$rowEvent['ContactPhone'].'<br />';
		}
		if (!empty($rowEvent['ContactEmail'])) {
			$contact .= '<a href="mailto:'.$rowEvent['ContactEmail'].'" title="Email contact">'.$rowEvent['ContactEmail'].'</a><br />';
		}
		$rowEvent['ContactString'] = $contact;
		
	} elseif ($action == 'edit') {
		/*
		 * Format dateTime stuff
		 */		
		$dateTimeStart = $rowEvent['StartDate'];
		$dateTimeEnd   = $rowEvent['EndDate'];
		
		$dateStartArray = explode(' ',$dateTimeStart);
		$dateEndArray   = explode(' ',$dateTimeEnd);
		$startDate      = $dateStartArray[0];
		$endDate        = $dateEndArray[0];
		
		/*
		 * Convert dates to ext format
		 */
		$rowEvent['StartDate'] = mySQLToExt($startDate);
		$rowEvent['EndDate']   = mySQLToExt($endDate);
			
		$startTimeArray = explode(':',$dateStartArray[1]);
		$endTimeArray   = explode(':',$dateEndArray[1]);
		
		$rowEvent['StartHour'] = $startTimeArray[0];
		$rowEvent['StartMin']  = $startTimeArray[1];

		$rowEvent['EndHour']   = $endTimeArray[0];
		$rowEvent['EndMin']    = $endTimeArray[1];
		
		if ($rowEvent['StartHour']>0) {
			if ($rowEvent['StartHour']>=12) {
				$rowEvent['StartAmPm'] = 'PM';
			} else {
				$rowEvent['StartAmPm'] = 'AM';
                                 /*
                                 * Drop leading 0 from hour
                                 */
                                $rowEvent['StartHour'] = substr($rowEvent['StartHour'],1,1);
			}
		} else {
			$rowEvent['StartAmPm'] = '';
		}
		if ($rowEvent['EndHour']>0) {
			if ($rowEvent['EndHour']>=12) {
				$rowEvent['EndAmPm'] = 'PM';
			} else {
				$rowEvent['EndAmPm'] = 'AM';
                                /*
                                 * Drop leading 0 from hour
                                 */
                                $rowEvent['EndHour'] = substr($rowEvent['EndHour'],1,1);
			}
		} else {
			$rowEvent['EndAmPm'] = '';
		}
		
		/*
		 * Check for properly formatted URL's
		 */
		if (!empty($rowEvent['ContactURL'])) {
			if (substr($rowEvent['ContactURL'],0,7) != 'http://') {
				$rowEvent['ContactURL'] = 'http://'.$rowEvent['ContactURL'];
			}
		}
		if (!empty($rowEvent['RegistrationLink'])) {
			if (substr($rowEvent['RegistrationLink'],0,7) != 'http://') {
				$rowEvent['RegistrationLink'] = 'http://'.$rowEvent['RegistrationLink'];
			}
		}
		
		$rowEvent['EventName']        = DBToField($rowEvent['EventName']);
		$rowEvent['EventDescription'] = DBToField($rowEvent['EventDescription']);
		$rowEvent['Location']         = DBToField($rowEvent['Location']);
		$rowEvent['LocationAddress']  = DBToField($rowEvent['LocationAddress']);
		$rowEvent['LocationCity']     = DBToField($rowEvent['LocationCity']);
		$rowEvent['Speakers']         = DBToField($rowEvent['Speakers']);
	}
	
	$stringJSON = Zend_Json::encode($rowEvent);
	return $stringJSON;
}

function deleteEvent($eventID) {
	global $dbname, $db, $db_selected;
	$sql = "DELETE from cdc_Calendar WHERE EventID = '$eventID'";
	$result = mysql_db_query($dbname,$sql);	
}

function displayEvent($date) {
	global $eventString,$dbname,$db,$db_selected,$pre;
	global $newDate,$newTime;
	$actUserid = $_SESSION[actUserid];
	$eventString = '';
	
	$sql = "SELECT * from cpo_calendar 
			WHERE Start_Date >= '$date'    AND 
			Start_Date <= '$date 23:59:59' AND 
			Userid = '$actUserid'";
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);	
	
	// Display events for this date
	$i = 0;
	$eventString .= '<table class="dataTable">';
	$eventString .= '<tr><th>Events for '.mysql_to_date2($date).'</th></tr>';
	while ($value = mysql_fetch_array($result)) {
		$eventID    = $value[ID];
		$eventType  = $value[Item_Type];
		$eventTitle = stripslashes($value[Title]);
		$eventDateFrom = $value[Start_Date];
		$eventDesc  = stripslashes($value[Description]);
		//$eventDescShort = htmlspecialchars(substr($eventDesc, 0, 50)).'...';
		//$eventDescShort2 = substr($eventDesc, 0, 50).'...';		
		convertDateTime($eventDateFrom);
		
		if (($i % 2) > 0) { $class = 'altRow'; }
		else { $class = ''; }
		$eventString .= '<tr class="'.$class.'"><td>';
		$eventString .= '<a href="#" onClick="confirmDelete('.$eventID.',\'event\'); return false;" title="Delete this event"><img src="'.$pre.'images/button_deleteSmall.gif" style="border: none;" alt="Delete this event"></a>';
		$eventString .= '&nbsp;<b>'.$eventTitle.'</b> <span style="color: #003399;">'.$newTime.'</span><div style="padding-left: 15px;">'.$eventDesc;
		if (!empty($eventType)) { $eventString .= '<br />Tag: <b>'.$eventType.'</b>'; }
		$eventString .= '</div>';
		
		$i++;
	}	
	$eventString .= '</table>';
		
	return $eventString;	
}

function getFutureEventsWithRegistration() {
	global $dbname,$db,$db_selected;
	$today = date('Y-m-d');
	
	$sql = "SELECT EventID,EventName FROM cdc_Calendar 
			WHERE
			(StartDate >= '$today' OR
			EndDate   >= '$today') AND
               Deleted = 0 AND
			RegistrationRequired = 1 
			ORDER BY StartDate ASC";
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);
	
	$returnString = '';
     $returnString .= '<p><b>Events Registration</b>';
	if ($rows>0) {
		$returnString .= '<ul class="subMenu">';
		while ($value = mysql_fetch_array($result)) {
			$returnString .= '<li><a href="#" onClick="openPopUpWindow(\'includes/popUpExport.php?export=registered&eventID='.$value['EventID'].'\'); return false;">'.$value['EventName'].'</a></li>';
		}
		$returnString .= '</ul></p>';
	} else {
		$returnString .= '<p>There are no events requiring registration at this time.</p>';
	}
	return $returnString;
}
?>